package com.jianbing.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.jianbing.dao.MongoDBDao;
import com.jianbing.entity.AccessToken;
import com.jianbing.entity.Customer;
import com.jianbing.entity.Result;
import com.jianbing.entity.TaskStatus;
import com.jianbing.service.GjjService;
import com.jianbing.util.Constants;
import com.jianbing.util.HttpClient;
import com.jianbing.util.SignUtil;
import com.jianbing.util.StringUtils;
import com.jianbing.util.TableUtil;
import com.mongodb.BasicDBObject;

import net.sf.json.JSONObject;

@Service
public class GjjServiceImpl implements GjjService {

	Logger logger = Logger.getLogger(GjjServiceImpl.class);

	@SuppressWarnings("static-access")
	@Override
	public Result getGjjData(Result result, JSONObject json) throws Exception {
		ModelMap model = new ModelMap();
		Date now = new Date();
		JSONObject jsonParam = JSONObject.fromObject(json.get("params"));
		MongoDBDao dbDao = new MongoDBDao();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("appKey", jsonParam.get("appKey"));
		Customer customer = dbDao.findOne(TableUtil.customer, Customer.class, queryObject);
		if (customer == null) {
			result.setCode(102);
			result.setMsg("无效的appKey");
			return result;
		}
		AccessToken accessToken = MongoDBDao.findOne(TableUtil.accessToken, AccessToken.class, queryObject);
		if (accessToken == null || accessToken.getActiveTime() < now.getTime()) {
			result.setCode(103);
			result.setMsg("token已超时");
			return result;
		}
		if ((jsonParam.getLong("timestamp") + Constants.accessTime * 1000) < now.getTime()
				|| !SignUtil.checkSign(json.getString("sign"), jsonParam, customer.getAppSecret())) {
			result.setCode(104);
			result.setMsg("签名错误");
			return result;
		}
		// 从数据仓库获取数据并校验
		String dataUrl = "";
		if (json.getString("type").equals(Constants.gjj)) {
			dataUrl = Constants.gjj_data_url;
		} else if (json.getString("type").equals(Constants.gjj_loan)) {
			dataUrl = Constants.gjj_loan_data_url;
		} else {
			result.setCode(105);
			result.setMsg("无此订单数据");
			return result;
		}
		String gjjDataResult = HttpClient.get(dataUrl + jsonParam.getString("orderSn"));
		if (StringUtils.isEmpty(gjjDataResult) || JSONObject.fromObject(gjjDataResult).getInt("code") != 0) {
			result.setCode(105);
			result.setMsg("无此订单数据");
			return result;
		}
		JSONObject gjjDataJson = JSONObject.fromObject(gjjDataResult);
		logger.info(json.getString("type") == Constants.gjj ? "公积金" : "公积金贷款" + "数据查询成功" + gjjDataJson);
		// 返回数据给合作方
		model.addAttribute("gjjData", gjjDataJson);
		result.setData(model);
		return result;
	}

	@Override
	public List<TaskStatus> queryGjjTaskStatus(String orderSn, Integer taskId, String status, String type) {
		BasicDBObject queryObject = new BasicDBObject();
		if (StringUtils.isNotEmpty(orderSn)) {
			queryObject.append("orderSn", orderSn);
		}
		if (StringUtils.isNotEmpty(status)) {
			queryObject.append("status", status);
		}
		if (taskId != null) {
			queryObject.append("taskId", taskId);
		}
		String tableName = "";
		if (type.equals(Constants.gjj)) {
			tableName = TableUtil.gjjTaskStatusTable;
		} else if (type.equals(Constants.gjj_loan)) {
			tableName = TableUtil.gjjLoanTaskStatusTable;
		} else {
			return null;
		}
		List<TaskStatus> gjjTaskStatusList = MongoDBDao.queryForList(tableName, TaskStatus.class, queryObject, null,
				null, null, null);
		return gjjTaskStatusList;
	}

	@Override
	public void updateGjjTaskStatus(String orderSn, Integer taskId, String status, String type) throws Exception {
		Date now = new Date();
		BasicDBObject queryObject = new BasicDBObject();
		queryObject.append("orderSn", orderSn);
		String tableName = "";
		if (type.equals(Constants.gjj)) {
			tableName = TableUtil.gjjTaskStatusTable;
		} else if (type.equals(Constants.gjj_loan)) {
			tableName = TableUtil.gjjLoanTaskStatusTable;
		} else {
			return;
		}
		TaskStatus gjjTaskStatus = MongoDBDao.findOne(tableName, TaskStatus.class, queryObject);
		if (gjjTaskStatus == null) {
			gjjTaskStatus = new TaskStatus();
			gjjTaskStatus.setOrderSn(orderSn);
			gjjTaskStatus.setTaskId(taskId);
			gjjTaskStatus.setStatus(status);
			gjjTaskStatus.setCreateTime(now);
			gjjTaskStatus.setUpdateTime(now);
			MongoDBDao.insert(tableName, gjjTaskStatus);
		} else {
			gjjTaskStatus.setStatus(status);
			gjjTaskStatus.setUpdateTime(now);
			gjjTaskStatus.setTaskId(taskId);
			MongoDBDao.update(tableName, queryObject, gjjTaskStatus);
		}
	}
}
